package com.example.xianji.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.xianji.Contant;
import com.example.xianji.R;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.example.xianji.widgets.CustomProgressDialog;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.Manifest;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class Main_set_up_photoActivity extends Activity implements OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback {
    private ImageView imageview_logo;
    private RelativeLayout set_up_photo_back;
    private LinearLayout layout;
    private PopupWindow show_popupWindow;
    private ListView show_listview;
    private String group[] = new String[]{"手机相册", "拍照", "取消"};
    private TextView photo_save;
    //    private SharedPreferences sp;
//    private Editor ed;
    private String photoStr = "";
    private CustomProgressDialog mCustomProgressDialog;
    private int Request_Permission_Take_Photo = 2;//拍照
    private int Request_Permission_Get_Photo = 1;//相册
    private Handler handle = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (mCustomProgressDialog != null) {
                        mCustomProgressDialog.dismiss();
                        mCustomProgressDialog = null;
                    }
                    break;
            }
        }
    };

    /**
     * 二进制转字符串
     *
     * @param b
     * @return
     */
    public static String byte2hex(byte[] b) {
        StringBuffer sb = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                sb.append("0" + stmp);
            } else {
                sb.append(stmp);
            }
        }
        return sb.toString();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main_set_up_photo);
        imageview_logo = (ImageView) findViewById(R.id.imageview_logo);
        photo_save = (TextView) findViewById(R.id.photo_save);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        set_up_photo_back = (RelativeLayout) findViewById(R.id.set_up_photo_relative_back);
        photo_save.setOnClickListener(this);
        imageview_logo.setOnClickListener(this);
        set_up_photo_back.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.imageview_logo) {
            Photo_show();
            show_popupWindow.showAtLocation(findViewById(R.id.set_up), Gravity.BOTTOM, 0, 0);
            show_listview.setAdapter(new ArrayAdapter<String>(Main_set_up_photoActivity.this, R.layout.information_show_photo_item, R.id.show_photo_item_text, group));

            show_listview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    if (group[position].equals("手机相册")) {
                        show_popupWindow.dismiss();
                        /**
                         * 下面这句话，与其它方式写是一样的效果，如果：
                         * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                         * intent.setType(""image/*");设置数据类型
                         * 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
                         * 这个地方小马有个疑问，希望高手解答下：就是这个数据URI与类型为什么要分两种形式来写呀？有什么区别？
                         */
                        String[] permission_Picture = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
                        if (permissionCheck(permission_Picture)) {
                            Intent intent = new Intent(Intent.ACTION_PICK, null);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(intent, 1);
                        } else {
                            ActivityCompat.requestPermissions(Main_set_up_photoActivity.this, permission_Picture, Request_Permission_Get_Photo);
                        }
                    }
                    if (group[position].equals("拍照")) {
                        show_popupWindow.dismiss();
                        /**
                         * 下面这句还是老样子，调用快速拍照功能，至于为什么叫快速拍照，大家可以参考如下官方
                         * 文档，you_sdk_path/docs/guide/topics/media/camera.html
                         * 我刚看的时候因为太长就认真看，其实是错的，这个里面有用的太多了，所以大家不要认为
                         * 官方文档太长了就不看了，其实是错的，这个地方小马也错了，必须改正
                         */
                        String[] permission_paizhao = {Manifest.permission.CAMERA};
                        if (permissionCheck(permission_paizhao)) {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intent, 2);
                        } else {
                            ActivityCompat.requestPermissions(Main_set_up_photoActivity.this, permission_paizhao, Request_Permission_Take_Photo);
                        }
                    }
                    if (group[position].equals("取消")) {
                        show_popupWindow.dismiss();
                    }
                }
            });
        } else if (v.getId() == R.id.photo_save) {
            if (photoStr.length() > 0) {
                mCustomProgressDialog = CustomProgressDialog.createDialog(this);
                mCustomProgressDialog.setCanceledOnTouchOutside(false);
                mCustomProgressDialog.show();
                set_up_photo();
            } else {
                Toast.makeText(this, "请先上传图片哦", Toast.LENGTH_SHORT).show();
            }
        } else if (v.getId() == R.id.set_up_photo_relative_back) {
            this.setResult(Contant.back_resultCode);
            this.finish();
        }
    }

    private boolean permissionCheck(String[] permissionManifest) {
        if (VERSION.SDK_INT >= 23) {
            boolean permissionState = true;
            for (String permission : permissionManifest) {
                if (ContextCompat.checkSelfPermission(this, permission)
                        != PackageManager.PERMISSION_GRANTED) {
                    permissionState = false;
                }
            }
            if (!permissionState) {
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (data != null) {
                    startPhotoZoom(data.getData());
                }
                break;
            case 2:
                if (data != null) {
                    if (data.getExtras() != null) {
                        Bitmap bitmap1 = (Bitmap) data.getExtras().get("data");
                        imageview_logo.setImageBitmap(bitmap1);
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        bitmap1.compress(Bitmap.CompressFormat.PNG, 100, stream);// (0 - 100)压缩文件
                        byte[] bt = stream.toByteArray();
                        photoStr = byte2hex(bt);
                    }
                }
                break;
            case 3:
                /**
                 * 非空判断大家一定要验证，如果不验证的话，
                 * 在剪裁之后如果发现不满意，要重新裁剪，丢弃
                 * 当前功能时，会报NullException，小马只
                 * 在这个地方加下，大家可以根据不同情况在合适的
                 * 地方做判断处理类似情况
                 *
                 */
                if (data != null) {
                    setPicToView(data);
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        if (requestCode == Request_Permission_Take_Photo) {
            //拍照
            if (grantResults.length > 0) {
                boolean take_photo_flag = false;
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                        take_photo_flag = true;
                    }
                }
                if (take_photo_flag) {
                    //申请成功，可以拍照
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                            .fromFile(new File(getCacheDir(),
                                    "xiaoma.jpg")));
                    startActivityForResult(intent, 2);
                } else {
                    Toast.makeText(this, "请先开通权限哦", Toast.LENGTH_SHORT).show();
                }

            }
        } else if (requestCode == Request_Permission_Get_Photo) {
            //相册
            if (grantResults.length > 0) {
                boolean take_photo_flag = false;
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                        take_photo_flag = true;
                    }
                }
                if (take_photo_flag) {
                    //申请成功，可以获取相册图片
                    Intent intent = new Intent(Intent.ACTION_PICK, null);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, 1);
                } else {
                    Toast.makeText(this, "请先开通权限哦", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "false");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 350);
        intent.putExtra("outputY", 350);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
        String[] pojo = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, pojo, null, null, null);
    }

    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        Bitmap photo = null;
        if (extras != null) {
            photo = extras.getParcelable("data");
            imageview_logo.setImageBitmap(photo);

            /**
             * 转化成16进制
             */
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.PNG, 100, stream);// (0 - 100)压缩文件
            byte[] bt = stream.toByteArray();
            photoStr = byte2hex(bt);
        }
    }

    /**
     * 上传头像数据
     */
    public void set_up_photo() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("avatar", photoStr);
        parms.addBodyParameter("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        httpUtils.send(HttpMethod.POST, Contant.photo, parms, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                handle.sendEmptyMessage(1);
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                JSONObject object;
                PreferenceEngine.getInstance().putInt(Constant.SP.NAME, Constant.SP.KEY_MY_XIANJI_SET, 2);
                try {
                    object = new JSONObject(arg0.result);
                    Toast.makeText(Main_set_up_photoActivity.this, object.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (object.getInt("status") == 1) {
                        new Handler() {

                            @Override
                            public void handleMessage(Message msg) {
                                super.handleMessage(msg);
                                Contant.login_resume = 1;
                                Main_set_up_photoActivity.this.setResult(Contant.delete_resultCode);
                                Main_set_up_photoActivity.this.finish();
                            }
                        }.sendEmptyMessage(0);
                    }
                    handle.sendEmptyMessage(1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void Photo_show() {
        layout = (LinearLayout) LayoutInflater.from(
                Main_set_up_photoActivity.this).inflate(
                R.layout.information_shoow_photo, null);
        show_listview = (ListView) layout.findViewById(R.id.information_photo_listview);
        show_listview.setCacheColorHint(0);
        show_popupWindow = new PopupWindow(layout, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        show_popupWindow.setBackgroundDrawable(new BitmapDrawable());
        show_popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        show_popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        show_popupWindow.update();
        show_popupWindow.setOutsideTouchable(true);
        show_popupWindow.setFocusable(true);
        show_popupWindow.setContentView(layout);
    }
}
